using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Threading.Tasks;
using CoachingOrganizer.Toolkit.Events;
using System.Threading;

namespace CoachingOrganizer.iOS.Helpers
{
    public static class UIHelper
    {
        public static void RegisterCellClass(UITableView table, string cellIdentifer)
        {
            using (NSString platformCellIdentifer = new NSString(cellIdentifer))
                table.RegisterClassForCellReuse(typeof(UITableViewCell), platformCellIdentifer);
        }

        public static void ShowDetailsStoryboad<TControlller>(string storyboardName, UIViewController targetController, Action<TControlller> initControllerDelegate) where TControlller : UIViewController
        {
            UIStoryboard detailsStoryboard = UIStoryboard.FromName(storyboardName, NSBundle.MainBundle);
            TControlller detailsController = (TControlller)detailsStoryboard.InstantiateInitialViewController();
            initControllerDelegate(detailsController);
            targetController.PresentViewController(detailsController, true, null);
        }

        public static int GetCollectionItemsCount<TItem>(IEnumerable<TItem> items)
        {
            return items == null ? 0 : items.Count();
        }

        public async static void InvokeWithResultCheck(Func<Task<ActionResult>> delegateToInvoke, string title, Func<Exception, string> getMessageDelegate)
        {
            ActionResult invokeResult = await delegateToInvoke();
            if (!invokeResult.IsValid)
            {
                UIAlertView messageView = new UIAlertView(title, getMessageDelegate(invokeResult.FailException), null, "OK");
                messageView.Show();
                messageView.Clicked += (s, e) => messageView.Dispose();
            }
        }

        public async static void InvokeLongOperation(Func<CancellationToken, Task> delegateToInvoke, string message)
        {
            using (UIActivityIndicatorView indicatorView = new UIActivityIndicatorView())
            {
                if (!string.IsNullOrWhiteSpace(message))
                    indicatorView.DrawString(message, indicatorView.Frame, UIFont.PreferredBody);
                indicatorView.StartAnimating();
                using (CancellationTokenSource cancellation = new CancellationTokenSource())
                    await delegateToInvoke(cancellation.Token);
                indicatorView.StopAnimating();
            }
        }
    }
}